import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Image, ScrollView,Alert,DeviceEventEmitter } from 'react-native';
import navigationSeevice from '../../../../../components/navigation/navigationSeevice';
import { style } from '../../../../../theme/style';
import HTTP from '../../../../../utils/http';
import { API, API_GENERATE } from '../../../../../config/api';
import { GLOBAL } from '../../../../../config/global';
import { Common } from '../../../../../component/common/Common';
import { ShortButton } from './_components/ShortButton';
import { ProductSelect } from './_components/ProductSelect';
import ToastUtil from '../../../../../utils/toast';
const scale = GLOBAL.SCALE;
const OPERATE_TYPE = {
	'CONTACTOR_ADD': '创建用户',
	'CONTACTOR_CHANGE': '用户变更',
}
export class ContractDetailPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '用户信息',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};
	constructor(props) {
		super(props);
		this.data = props.navigation.state.params.data || {};
		this.baseData = props.navigation.state.params.baseData || {};
		this.ifEdit = props.navigation.state.params.ifEdit;
		this.choice = props.navigation.state.params.choice || {};

		this.state = {
			goodsModal: false,
			goodsTreeList: [],
			logList: [],
		}
		this.contractType=[
			'不带入','姓名+邮箱','姓名+手机号'
		]
	}

	componentWillMount () {
		this._init();
	}

	_init = async () => {
		const goodsTreeList = await this._getGoodsTreeList();
		const logList = await this._getLogList();

		this.setState({ goodsTreeList, logList });
	}

	//操作记录
	_getLogList = async () => {
		let { companyId, contactorId } = this.data;
		const logList = await HTTP.POST(API_GENERATE(API.CONTRACTOR_LOG_LIST), { companyId, contractorId: contactorId, corpId: this.choice.corpId });
		return logList;
	}

	//操作记录详情
	_getLogDetail = async (item) => {
		const preDetail = await HTTP.POST(API_GENERATE(API.CONTRACTOR_LOG), { id: item.preLogId });
		navigationSeevice.navigate('ContractorChangeDetail', { changeDetail: item, preDetail });
	}

	//经营品类
	_getGoodsTreeList = async (searchCode) => {
		let { companyId, contactorId } = this.data;
		const goodsTreeList = await HTTP.POST(API_GENERATE(API.CONTRACTOR_GOODSTREE_LIST), { companyId, contractorId: contactorId, corpId: this.choice.corpId, ...searchCode });
		return goodsTreeList;
	}

	_cancelPress (a) {
		this.setState({ goodsModal: false })
	}

	async _delete () {
		let { companyId, contactorId } = this.data;
		let res = await HTTP.POST(API_GENERATE(API.CUSTOMER_DELETE), { 
			companyId, contactorId, corpId: this.choice.corpId
		});
		if(res){
			ToastUtil.showSuccess('删除成功').then(() => {
				this.props.navigation.state.params.callback();
				this.props.navigation.goBack()
				DeviceEventEmitter.emit('qycyUpdate');
			})
		}
	}

	_renderBaseInfo () {
		let { contactorName, mobileNo, contactorPosition, contactorAddress,attachedFlag,email } = this.data;
		return (
			<View style={styles.detailBase}>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>联系人</Text>
					<Text style={[styles.commonText]}>{contactorName || '--'}</Text>
				</View>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>电话</Text>
					<Text style={[styles.commonText]}>{mobileNo || '--'}</Text>
				</View>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>经营品类</Text>
					<Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => this.setState({ goodsModal: true })}>【查看品类】</Text>
				</View>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>合同带入</Text>
					<Text style={[styles.commonText]}>{attachedFlag?this.contractType[attachedFlag-1] : '--'}</Text>
				</View>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>职位</Text>
					<Text style={[styles.commonText]}>{contactorPosition || '--'}</Text>
				</View>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>邮箱</Text>
					<Text style={[styles.commonText]}>{email || '--'}</Text>
				</View>
				<View style={styles.row}>
					<Text style={[styles.commonText, styles.label]}>地址</Text>
					<Text style={[styles.commonText]}>{contactorAddress || '--'}</Text>
				</View>
				
			</View>
		)
	}

	//操作日志
	_renderLogView () {
		const { logList } = this.state;
		return (
			<View style={styles.logContainer}>
				<ScrollView style={[styles.modalBody]}>
					{
						logList.map((item, index) => {
							const { updateTime, organName, staffName, operateType, logId } = item || {};
							const remark = OPERATE_TYPE[operateType];
							return (
								<View style={[styles.progressItem]} key={index}>
									{index == logList.length - 1 ? null : <View style={styles.logLine}></View>}
									<View style={styles.nodeIcon}></View>
									<Text style={styles.nodeStatus}>操作</Text>
									<Text style={styles.nodeTitle}>{updateTime && updateTime.substring(0, 16)}</Text>
									<View>
										<Text style={[styles.nodeInfo, { marginTop: 5 * scale }]}>{organName || '--'}：{staffName || '--'}</Text>
										<Text style={[styles.nodeInfo, { marginTop: 2 * scale }]}>备注：{remark}
											<Text style={{ color: style.color.themeColor }} onPress={() => this._getLogDetail(item)}>{operateType == 'CONTACTOR_CHANGE' ? '【查看】' : ''}</Text>
										</Text>
									</View>
									<View style={{ height: 30 * scale }}></View>
								</View>
							)
						})
					}
				</ScrollView>
			</View>
		)
	}

	render () {
		const { goodsModal, goodsTreeList, logList } = this.state;
		return (
			<View style={styles.detail}>
				{this._renderBaseInfo()}
				{logList && logList.length ? this._renderLogView() : null}

				{
					this.ifEdit ? 
					<View style={{flexDirection:'row',position: 'absolute',bottom: 30 * scale}}>
						<TouchableOpacity style={[styles.btn,{marginRight:50*scale}]} onPress={() => {
							navigationSeevice.navigate('EnterpriseEditContactPage', {
								companyName: this.baseData.companyName,
								countryCode: this.baseData.countryCode,
								companyId:this.baseData.companyId,
								vo: this.data,
								choice: this.choice
							})
						}} >
							<Text style={styles.btnText}>编辑</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.btn} onPress={() => {
							Alert.alert('提示', '是否确定删除该联系人', [
								{ text: '取消', onPress: () => { console.log('取消') } },
								{ text: '确定', onPress: () => { this._delete() } }
							]);
						}} >
							<Text style={styles.btnText}>删除</Text>
						</TouchableOpacity>
						{/* <ShortButton btnText={'删除'} onPress={() => {
							
						}} /> */}
					</View>
					 : null
				}

				{
					goodsModal ?
						<ProductSelect
							// confirmPress={this._confirmPress}
							cancelPress={() => this._cancelPress()}
							searchPress={(searchCode) => this._getGoodsTreeList(searchCode)}
							data={goodsTreeList}
							modalVisible={goodsModal} />
						: null
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	detail: {
		flex: 1,
		alignItems: 'center',
		padding: 20 * scale,
		paddingTop: 30 * scale
	},
	detailBase: {
		width: '100%'
	},
	row: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 6 * scale,
		paddingBottom: 22 * scale,
	},
	commonText: {
		fontSize: 12 * scale,
		color: '#000',
		marginRight: 10 * scale,
	},
	label: {
		fontWeight: '600',
		width: 80 * scale
	},
	logContainer: {
		maxHeight: 320 * scale,
		width: '90%',
		backgroundColor: style.color.bgGray,
		padding: 18 * scale,
	},
	modalBody: {
		paddingTop: 10 * scale,
	},
	progressItem: {
		position: 'relative',
		paddingLeft: 14 * scale,
		paddingLeft: 48 * scale,
	},
	logLine: {
		height: '100%',
		width: 1 * scale,
		backgroundColor: '#EBEDF0',
		position: 'absolute',
		left: 32 * scale,
		top: 5 * scale
	},
	nodeIcon: {
		width: 5 * scale,
		height: 5 * scale,
		backgroundColor: '#848A96',
		borderRadius: 5 * scale,
		position: 'absolute',
		top: 2 * scale,
		left: 30 * scale,
	},
	nodeStatus: {
		position: 'absolute',
		fontSize: 10 * scale,
		top: -2 * scale,
		left: 0 * scale,
		color: '#959BA8'
	},
	nodeTitle: {
		fontSize: 10 * scale,
		marginTop: -3 * scale,
		color: '#959BA8'
	},
	nodeInfo: {
		fontSize: 10 * scale,
		color: '#959BA8',
		lineHeight: 14 * scale,
	},
	btn: {
		backgroundColor: style.color.themeColor,
		width: 80 * scale,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
		borderRadius: 14 * scale,
	},
	btnText: {
		color: '#fff',
		textAlign: 'center',
		fontSize: 14 * scale,
		fontWeight: 'bold'
	},
})